package com.xs.ai.services;

import com.xs.ai.dto.EmailAnalysisResult;
import com.xs.ai.dto.ReplySuggestion;
import com.xs.ai.dto.UserPreferences;
import com.xs.ai.entity.ContactImportance;
import com.xs.ai.entity.Email;
import com.xs.ai.entity.User;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailAnalysisService {
    
    private final ChatClient chatClient;
    private final ContactImportanceService contactImportanceService;
    private final UserBehaviorLearningService behaviorLearningService;
    private final ObjectMapper objectMapper;
    
    /**
     * 分析邮件并生成AI见解
     */
    public EmailAnalysisResult analyzeEmail(Email email, User user) {
        log.info("开始分析邮件: {}", email.getMessageId());
        
        // 1. 获取联系人重要性
        ContactImportance senderImportance = contactImportanceService
            .getContactImportance(user.getId(), email.getSenderEmail());
        
        // 2. 获取用户历史偏好
        UserPreferences userPrefs = behaviorLearningService
            .getUserPreferences(user.getId());
        
        // 3. 构建AI提示词
        String prompt = buildEmailAnalysisPrompt(email, senderImportance, userPrefs);
        
        // 4. 调用AI分析
        String aiResponse = chatClient.call(new Prompt(new UserMessage(prompt)));
        
        // 5. 解析AI响应
        EmailAnalysisResult result = parseAIResponse(aiResponse);
        
        // 6. 保存分析结果
        saveAnalysisResult(email, result);
        
        log.info("邮件分析完成 - 优先级: {}, 类别: {}", 
            result.getPriority(), result.getCategory());
        
        return result;
    }
    
    private String buildEmailAnalysisPrompt(Email email, 
                                           ContactImportance sender, 
                                           UserPreferences prefs) {
        return String.format("""
            你是一位高级CEO执行助理。请分析以下邮件并提供结构化的JSON响应。
            
            ## 邮件信息
            发件人: %s (%s)
            主题: %s
            正文: %s
            收件时间: %s
            
            ## 发件人重要性数据
            重要性评分: %.2f (0-1范围)
            职位: %s
            关系类型: %s
            历史互动次数: %d
            平均回复时间: %d分钟
            
            ## CEO偏好设置
            优先关注领域: %s
            典型工作时间: %s
            委托偏好: %s
            
            ## 分析要求
            请以JSON格式返回以下信息，不要包含任何markdown标记或额外文本:
            
            {
              "priority": "URGENT_CRITICAL | HIGH_IMPORTANCE | MEDIUM_IMPORTANCE | LOW_IMPORTANCE | AUTO_ARCHIVE",
              "priorityReason": "为什么给出这个优先级的简短理由",
              "category": "meeting_request | decision_needed | info_only | client_communication | internal_update | partnership等",
              "sentiment": "positive | neutral | negative | urgent",
              "summary": "2-3句话的邮件摘要",
              "keyPoints": ["关键点1", "关键点2", "关键点3"],
              "suggestedActions": [
                {
                  "action": "reply_immediately | schedule_meeting | delegate | archive | add_to_task",
                  "description": "具体建议描述",
                  "priority": "high | medium | low"
                }
              ],
              "extractedDeadlines": [
                {
                  "description": "截止事项描述",
                  "deadline": "ISO日期格式"
                }
              ],
              "requiresDecision": true/false,
              "decisionDescription": "如果需要决策，描述需要决策的内容",
              "canDelegate": true/false,
              "suggestedDelegateTo": "建议委托给的角色或部门",
              "estimatedResponseTime": "立即 | 1小时内 | 今日内 | 本周内 | 可延后",
              "confidenceScore": 0.0-1.0
            }
            
            注意:
            1. 如果发件人重要性评分>0.8，优先级至少为HIGH_IMPORTANCE
            2. 包含"紧急"、"急"、"ASAP"等词汇应提升优先级
            3. 会议邀请需要检查时间冲突
            4. 决策类邮件需要标记requiresDecision为true
            5. 仅返回JSON，不要有其他内容
            """,
            email.getSenderEmail(),
            email.getSenderName(),
            email.getSubject(),
            truncateText(email.getBodyText(), 1000),
            email.getReceivedAt(),
            sender.getImportanceScore(),
            sender.getContactTitle(),
            sender.getRelationshipType(),
            sender.getInteractionCount(),
            sender.getAvgResponseTimeMinutes(),
            String.join(", ", prefs.getPriorityAreas()),
            prefs.getWorkingHours(),
            prefs.getDelegationStyle()
        );
    }
    
    private EmailAnalysisResult parseAIResponse(String aiResponse) {
        try {
            // 移除可能的markdown标记
            String cleanedResponse = aiResponse
                .replaceAll("```json\\s*", "")
                .replaceAll("```\\s*", "")
                .trim();
            
            return objectMapper.readValue(cleanedResponse, EmailAnalysisResult.class);
        } catch (Exception e) {
            log.error("解析AI响应失败: {}", e.getMessage());
            return createFallbackAnalysis();
        }
    }
    
    /**
     * 生成邮件回复建议
     */
    public List<ReplySuggestion> generateReplySuggestions(Email email, User user) {
        // 获取用户历史回复风格
        String userReplyStyle = behaviorLearningService.getUserReplyStyle(user.getId());
        
        String prompt = String.format("""
            你是CEO的执行助理。请为以下邮件生成3种不同风格的回复建议。
            
            ## 原始邮件
            发件人: %s
            主题: %s
            正文: %s
            
            ## CEO回复风格特征
            %s
            
            ## 要求
            请生成3种回复选项，以JSON数组格式返回，不要有markdown标记:
            
            [
              {
                "type": "quick_confirm",
                "subject": "回复主题",
                "body": "简短确认型回复(2-3句话)",
                "tone": "professional",
                "useCase": "快速确认或简单回应"
              },
              {
                "type": "detailed_response",
                "subject": "回复主题",
                "body": "详细回复(包含具体信息和后续安排)",
                "tone": "professional",
                "useCase": "需要详细说明或提供信息时使用"
              },
              {
                "type": "delegate",
                "subject": "转发主题",
                "body": "委托给团队成员的转发内容",
                "suggestedDelegate": "建议委托的角色",
                "tone": "directive",
                "useCase": "适合委托处理的情况"
              }
            ]
            
            注意:
            1. 保持CEO的专业形象和沟通风格
            2. 回复要简洁有力，避免冗余
            3. 根据邮件内容提供最合适的回复
            4. 仅返回JSON数组
            """,
            email.getSenderEmail(),
            email.getSubject(),
            truncateText(email.getBodyText(), 800),
            userReplyStyle
        );
        
        String aiResponse = chatClient.call(new Prompt(new UserMessage(prompt)));
        return parseReplySuggestions(aiResponse);
    }
    
    private String truncateText(String text, int maxLength) {
        if (text == null) return "";
        return text.length() > maxLength ? 
            text.substring(0, maxLength) + "..." : text;
    }
    
    // 其他辅助方法...
}